package com.sznaner.tool.util;

import android.util.Log;

import com.sznaner.tool.bean.WallpaperBean;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Stack;

public class MyFileUtil {

    //删除文件夹所有文件
    public static void deleateAllFile(String dirpath){
        if(!MyPathUtil.checkPath(dirpath)) return;
        File filePath = new File(dirpath);

        File[] files = filePath.listFiles();
        LogUtil.debugLog("删除文件总数:"+files.length);
        for(int i=0; i< files.length; i++){
            File childFile = files[i];
            LogUtil.debugLog("删除文件:"+childFile.getAbsolutePath());
            MyFileUtil.deleteFile(childFile.getAbsolutePath());
        }
    }

    /**
     * 删除单个文件
     * @param   filePath    被删除文件的文件名
     * @return 文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            return file.delete();
        }
        return false;
    }

    /**
     * 复制整个文件夹内容
     * @param oldPath String 原文件路径 如：c:/fqf
     * @param newPath String 复制后路径 如：f:/fqf/ff
     * @return boolean
     */
    public static void copyFolder(String oldPath, String newPath) {

        if(!MyPathUtil.checkPath(oldPath)) return;//文件源不存在直接return

        try {
            MyPathUtil.checkPathAndCreat(newPath);//如果文件夹不存在 则建立新文件夹
            File a=new File(oldPath);
            String[] file=a.list();
            File temp=null;
            for (int i = 0; i < file.length; i++) {
                if(oldPath.endsWith(File.separator)){
                    temp=new File(oldPath+file[i]);
                }
                else{
                    temp=new File(oldPath+File.separator+file[i]);
                }

                if(temp.isFile()){
                    FileInputStream inStream = new FileInputStream(temp);
                    FileOutputStream outStream = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ( (len = inStream.read(b)) != -1) {
                        outStream.write(b, 0, len);
                    }
                    inStream.close();
                    // 刷新数据并将数据转交给操作系统
                    outStream.flush();
                    // 强制系统缓冲区与基础设备同步
                    // 将系统缓冲区数据写入到文件
                    outStream.getFD().sync();
                    outStream.close();

                }
                if(temp.isDirectory()){//如果是子文件夹
                    copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
                }
            }
        }
        catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }

    }



    //扫描所有文件
    public static ArrayList<String> scanFiles(String path) {
        return scanFiles(path,new ArrayList<String>(),null);
    }


    /**
     *扫描文件
     *@params path 路径
     *@params path exceptDirs 排除的字文件夹数组
     *@params path types 要扫描哪些格式的文件例如:.mp3 .png
     *@return
     */
    public static ArrayList<String> scanFiles(String path, List<String> exceptDirs, List<String>types) {

        ArrayList<String> mFileList = new ArrayList<>();

        if(path == null) return mFileList;

        if(!MyPathUtil.checkPath(path)) return mFileList;

        mFileList.clear();
        File file = new File(path);
        Stack<File> folderStack = new Stack<>();
        folderStack.push(file);

        long starttime = System.currentTimeMillis();

        while (!folderStack.empty()) {

            file = folderStack.pop();
            File[] files = file.listFiles();

            //　内部排序
            Arrays.sort(files, new Comparator<File>() {
                @Override
                public int compare(File o1, File o2) {
                    return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase());
                }
            });

            for (int i = 0; i < files.length; i++) {
                String fullfilepath = files[i].getAbsolutePath();

                if(exceptDirs.size()>0 && files[i].isDirectory()){
                    if(exceptDirs.contains(files[i].getName())){
                        continue;
                    }
                }

                if (files[i].isDirectory() && !"./".equals(files[i].getName())) {
                    folderStack.push(files[i]);
                    String ext = MyPathUtil.getExt(fullfilepath);
                    if(types.size() > 0){
                        if(ext !=null && types.contains(ext)){
                            mFileList.add(fullfilepath);
                        }
                    }else {
                        mFileList.add(fullfilepath);
                    }
                } else {
                    String ext = MyPathUtil.getExt(fullfilepath);
                    if(types.size() > 0){
                        if(ext !=null && types.contains(ext)){
                            mFileList.add(fullfilepath);
                        }
                    }else {
                        mFileList.add(fullfilepath);
                    }
                }
            }
        }

        long timeuse = System.currentTimeMillis() - starttime;

        Arrays.sort(mFileList.toArray());

        //　外部排序
        mFileList.sort(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });


        ArrayList<String> resultFileList = new ArrayList<>();
        //排除.开头文件
        for (String tempPath : mFileList){
            File tempFile = new File(tempPath);
            String fileName = MyPathUtil.getName(tempFile);
            if(fileName.length()>0 && !fileName.substring(0,1).equals(".")){
                resultFileList.add(tempPath);
            }
        }
        return resultFileList;
    }

    //扫描路径获取图片
    public static  List<WallpaperBean> scanImagesWithPath(String path){
        List<WallpaperBean> result = new ArrayList<>();

        //排除文件夹
        List<String> exceptDir = new ArrayList<>();
        exceptDir.add("Android");

        //扫描哪些格式
        List<String> types = new ArrayList<>();
        types.add(".jpg");
        types.add(".png");

        List<String> allFiles = FileScannerUtil.scanFiles(path,exceptDir,types);
        for (String fpath :allFiles){

            result.add(new WallpaperBean(fpath,MyPathUtil.getNameAndExt(fpath)));
        }
        return result;
    }


}
